package com.example.bloodbankapplication.location;

import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;

public class MyLocation implements OnConnectionFailedListener ,ConnectionCallbacks{
	private Context mContext;
	private LocationClient locationClient;
	private LocationListener mLocationListener;
	private Double lat,lon;
	private String donorAddress;
	public MyLocation(Context context,String address) {

		mContext = context;
		donorAddress = address;
	}

	public void getLocations() {
		locationClient = new LocationClient(mContext, this, this);
		locationClient.connect();
	}

	public void onConnected(Bundle connectionHint) {

		LocationRequest lRequest = LocationRequest.create().setInterval(1000).setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
		mLocationListener = new LocationListener() {

			@Override
			public void onLocationChanged(Location location) {
				Log.i("NCS","in onLocation Changed");
				lat = location.getLatitude();
				lon = location.getLongitude();
				new MyAsynTask().execute(String.valueOf(lat),String.valueOf(lon));
			}   
		};

		locationClient.requestLocationUpdates(lRequest, mLocationListener);


	}

	public void onDisconnected() {

	}

	public void onConnectionFailed(ConnectionResult result) {

	}



 class MyAsynTask extends AsyncTask<String, Void, Void>{

	@Override
	protected Void doInBackground(String... params) {
		try {
			
			getLocationInfo(params[0], params[1]);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}


public  JSONObject getLocationInfo(String lat,String lon) {

	HttpGet httpGet = new HttpGet("http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lon+"&sensor=false");
	HttpClient client = new DefaultHttpClient();
	HttpResponse response;
	StringBuilder stringBuilder = new StringBuilder();

	try {
		response = client.execute(httpGet);
		HttpEntity entity = response.getEntity();
		InputStream stream = entity.getContent();
		int b;
		while ((b = stream.read()) != -1) {
			stringBuilder.append((char) b);
		}
	} catch (ClientProtocolException e) {
	} catch (IOException e) {
	}

	JSONObject jsonObject = new JSONObject();
	
	Log.i("NCS","stringBuilder.toString() :"+stringBuilder.toString());

	try {
		jsonObject = new JSONObject(stringBuilder.toString());
		getGeoPoint(jsonObject);
	} catch (JSONException e) {
		Log.i("NCS", "Exception 1 is  :  " + e.getMessage());
	}


	return jsonObject;
}


public  void getGeoPoint(JSONObject jsonObject) {


	try {
		locationClient.removeLocationUpdates(mLocationListener);
		JSONArray results = jsonObject.getJSONArray("results");
		JSONObject js = results.getJSONObject(0);
		String address = js.getString("formatted_address");
		Log.i("NCS","My Address :"+address);

		/*String uri = "http://maps.google.com/maps?saddr="+adress+"&daddr="+"Begumpet, Hyderabad, Andhra Pradesh";
			 Intent i = new  Intent(Intent.ACTION_VIEW,Uri.parse("geo:0,0?q="+"Begumpet, Hyderabad, Andhra Pradesh"));       
			Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uri));
			intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
			startActivity(i); */
		String uri = "http://maps.google.com/maps?saddr="+address+"&daddr="+donorAddress;
		Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uri));
		intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
		mContext.startActivity(intent);    
	} catch (JSONException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}


}


}
